package cn.fr4nk.crawler.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ThreadPool implements InitializingBean, DisposableBean {

	private static Log log = LogFactory.getLog(ThreadPool.class);

	protected ExecutorService executor;
	protected String poolName = "ThreadPool";
	protected int poolSize = 10;

	/**
	 * 添加任务到线程池
	 * 
	 * @param r
	 */
	public void addRunnable(Runnable r) {
		if (null != executor)
			executor.execute(r);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern(poolName + "-%d").build();
		executor = Executors.newFixedThreadPool(poolSize, factory);
	}

	@Override
	public void destroy() throws Exception {
		// 销毁
		if (executor != null) {
			executor.shutdown();
			try {
				// Wait a while for existing tasks to terminate
				if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
					executor.shutdownNow();
					if (!executor.awaitTermination(60, TimeUnit.SECONDS))
						log.error("线程池[" + poolName + "]没有正常停止...");
				}
			} catch (InterruptedException ie) {
				executor.shutdownNow();
				Thread.currentThread().interrupt();
			}
			log.info("处理线程池正常停止....");
		}
	}

	public ExecutorService getExecutor() {
		return executor;
	}

	public String getPoolName() {
		return poolName;
	}

	public int getPoolSize() {
		return poolSize;
	}

	public void setExecutor(ExecutorService executor) {
		this.executor = executor;
	}

	public void setPoolName(String poolName) {
		this.poolName = poolName;
	}

	public void setPoolSize(int poolSize) {
		this.poolSize = poolSize;
	}

}
